package com.vcredit.creditcat.service.product;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.vcredit.bird.vo.product.ddq.CrediDdqAmountParamDto;
import com.vcredit.bird.vo.product.ddq.CreditDdqDecisionResult;
import com.vcredit.bird.vo.product.ddq.CreditDdqParamDto;
import com.vcredit.creditcat.enumtype.AuthItemEnum;
import com.vcredit.creditcat.enumtype.MerchantProductEnum;
import com.vcredit.creditcat.exception.ProductCanNotApplyException;
import com.vcredit.creditcat.exception.ResourceException;
import com.vcredit.creditcat.model.Cust;
import com.vcredit.creditcat.model.CustProductApply;
import com.vcredit.creditcat.model.ProductItem;
import com.vcredit.creditcat.service.CustProductApplyService;
import com.vcredit.creditcat.service.product.enumtype.ProductEnumType;
import com.vcredit.creditcat.util.ConcurrentDateUtil;
import com.vcredit.creditcat.util.Utility;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.BeanUtil;
import com.vcredit.framework.util.JacksonUtil;

/**
 * @author 张新功
 */
@Service("creditDdq")
public class CreditDDCashApplyService implements IProductApplyService {
  //  private Logger logger = LoggerFactory.getLogger(CreditDDCashApplyService.class);
  //  @Autowired
  //  private CustService custService;
  @Autowired
  private CustProductApplyService custProductApplyService;
  //  @Autowired
  //  private ProductItemService productItemService;
  //  @Autowired
  //  private CustProductManager custProductManager;
  @Autowired
  @Qualifier("productStrategyContext")
  private ICreditCommonService creditCommonApplyService;

  //  @Autowired
  //  @Qualifier("creditDdqService")
  //  private ICreditProductService creditProductService;


  @Log
  @Override
  public Object applyCommit(Long custId, Long productId,Map<String,String> otherParams) throws Exception {

    return null;

  }

  @Log
  @Override
  public void queryLimit(CustProductApply custProductApply) throws Exception {
    CustProductApply creditAmoutResult =
        creditCommonApplyService.getCreditAmoutResult(custProductApply,
            MerchantProductEnum.creditKak);
    if (null == creditAmoutResult) {
      return;
    }
    creditCommonApplyService.saveCustProductApply(creditAmoutResult);
  }




  @Override
  public Boolean hasAlreadyAuditAmount(Object resultDto) throws ProductCanNotApplyException {
    // TODO Auto-generated method stub
    return null;
  }


  /** 
   * TODO 简单描述该方法的实现功能（可选）. 
   * @see com.vcredit.creditcat.service.product.IProductApplyService#getCreditAmountParam() 
   */
  @Override
  public Object getCreditAmountParam(Cust cust, ProductItem productItem) {
    CrediDdqAmountParamDto amountParamDto =
        new CrediDdqAmountParamDto(cust.getCustIdno(), ConcurrentDateUtil.formatDateTime(new Date()), "");
    try {
      String obj2Json = JacksonUtil.Obj2Json(amountParamDto);
      Map<String, Object> json2Map = JacksonUtil.Json2Map(obj2Json);

      StringBuilder sb = new StringBuilder();
      for (Entry<String, Object> entry : json2Map.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        if (key.matches("^Sign$")) {
          continue;
        }
        sb.append(key).append("=").append(value).append(",");
      }
      String resultString = sb.toString();
      resultString = resultString.substring(0, resultString.length() - 1);
      String[] arr = resultString.split(",");
      Arrays.sort(arr);
      String sign = StringUtils.join(arr, "+");
      amountParamDto.setSign(sign);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return amountParamDto;
  }

  /** 
   * TODO 简单描述该方法的实现功能（可选）. 
   * @see com.vcredit.creditcat.service.product.IProductApplyService#getAudInputParam() 
   */
  @Override
  public Object getAudInputParam(Object dto) {
    return null;
  }

  /** 
   * TODO 简单描述该方法的实现功能（可选）. 
   * @see com.vcredit.creditcat.service.product.IProductApplyService#getSaveAuditResultParam(com.vcredit.bird.vo.product.ProductOutputDto) 
   */
  @Override
  public CustProductApply getSaveAuditResultParam(Long custId, Long productId, Object outputDto)
      throws Exception {
    CustProductApply custProductApply = new CustProductApply();

    CustProductApply custProductApplySelect =
        custProductApplyService.findNewApplyProduct(productId, custId);
    boolean isNull = null == custProductApplySelect;
    String flowNo =
        isNull
            ? Utility.nextCode(MerchantProductEnum.creditDdq.name().toUpperCase())
            : custProductApplySelect.getFlowNo();
    custProductApply.setFlowNo(flowNo);
    custProductApply.setCustId(custId);
    custProductApply.setProductId(productId);
    if (!isNull) {
      custProductApply.setApplyId(custProductApplySelect.getApplyId());
    }
    custProductApply.setIsApply(true);
    custProductApply.setAuditTime(ConcurrentDateUtil.formatDateTime(new Date()));
    custProductApply.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(new Date()));
    CreditDdqDecisionResult creditResultDto =
        JacksonUtil.Json2Obj(JacksonUtil.Obj2Json(outputDto),
            new TypeReference<CreditDdqDecisionResult>() {});
    Integer status = creditResultDto.getAuditResult();
    if (null != status) {
      switch (status) {
        case 0://授信拒绝
          custProductApply.setAuditResult(0);
          custProductApply.setRejectMsg(creditResultDto.getRejectMsg());
          break;
        case 1://授信通过
          custProductApply.setCreditAmt(Integer.parseInt(creditResultDto.getCreditAmt()));
          custProductApply.setCreditExpiretime(creditResultDto.getCreditExpiretime());
          custProductApply.setAuditResult(1);
          custProductApply.setIsApply(false);
          break;
        case -1://授信异常
          custProductApply.setAuditResult(0);
          custProductApply.setRejectMsg(creditResultDto.getRejectMsg());
          break;
        default:
          custProductApply.setAuditResult(0);
          custProductApply.setRejectMsg("额度申请失败");
          break;
      }
    }

    return custProductApply;
  }

  /** 
   * TODO 简单描述该方法的实现功能（可选）. 
   * @see com.vcredit.creditcat.service.product.IProductApplyService#getProductCommitParam(java.util.Map) 
   */
  @Override
  public Object getProductCommitParam(Long productId, Cust cust, Map<AuthItemEnum, Object> itemMap,Map<String,String> otherParams)
      throws ResourceException, Exception {
    CreditDdqParamDto creditDdqParamDto = new CreditDdqParamDto();
    BeanUtil.copy(cust, creditDdqParamDto);
    for (Entry<AuthItemEnum, Object> entrySet : itemMap.entrySet()) {
      BeanUtil.copy(entrySet.getValue(), creditDdqParamDto);
    }
    String salaryKey =
        creditCommonApplyService.getProductEnumCode(productId,
            ProductEnumType.monthlyIncome.getCode(), creditDdqParamDto.getSalaryKey());
    String educationKey =
        creditCommonApplyService.getProductEnumCode(productId, ProductEnumType.education.getCode(),
            creditDdqParamDto.getEducationKey());
    String marriageKey =
        creditCommonApplyService.getProductEnumCode(productId, ProductEnumType.marriage.getCode(),
            creditDdqParamDto.getMarriageKey());
    String professionTypeKey =
        creditCommonApplyService.getProductEnumCode(productId, ProductEnumType.job.getCode(),
            creditDdqParamDto.getProfessionKey());
    creditDdqParamDto.setSalaryValue(salaryKey);
    creditDdqParamDto.setEducationValue(educationKey);
    creditDdqParamDto.setMarriageValue(marriageKey);
    creditDdqParamDto.setProfessionValue(professionTypeKey);
    creditDdqParamDto.setCensusIsLiveCityValue(String.valueOf(creditDdqParamDto
        .getCensusIsLiveCity()));
    creditDdqParamDto
        .setHasAccumulationValue(String.valueOf(creditDdqParamDto.getHasAccumulation()));
    creditDdqParamDto.setTimestamp(ConcurrentDateUtil.formatDateTime(new Date()));
    //转成base64
    creditDdqParamDto.setIdFront(creditCommonApplyService.getBase64StringByCode(creditDdqParamDto
        .getIdFront()));
    creditDdqParamDto.setIdBack(creditCommonApplyService.getBase64StringByCode(creditDdqParamDto
        .getIdBack()));
    creditDdqParamDto.setIdFace(creditCommonApplyService.getBase64StringByCode(creditDdqParamDto
        .getIdFace()));

    String obj2Json = JacksonUtil.Obj2Json(creditDdqParamDto);
    Map<String, Object> json2Map = JacksonUtil.Json2Map(obj2Json);

    StringBuilder sb = new StringBuilder();
    for (Entry<String, Object> entry : json2Map.entrySet()) {
      String key = entry.getKey();
      Object value = entry.getValue();
      if (key.matches("(^Identity.+Image$)|(Sign)")) {
        continue;
      }
      sb.append(key).append("=").append(value).append(",");
    }
    String resultString = sb.toString();
    resultString = resultString.substring(0, resultString.length() - 1);
    String[] arr = resultString.split(",");
    Arrays.sort(arr);
    String sign = StringUtils.join(arr, "+");
    creditDdqParamDto.setSign(sign);
    return creditDdqParamDto;
  }

  /** 
   * TODO 简单描述该方法的实现功能（可选）. 
   * @see com.vcredit.creditcat.service.product.IProductApplyService#getProductCheckCreditParam(com.vcredit.creditcat.model.Cust) 
   */
  @Override
  public Object getProductCheckCreditParam(Cust cust) {
    return null;
  }

  /** 
   * TODO 简单描述该方法的实现功能（可选）. 
   * @see com.vcredit.creditcat.service.product.IProductApplyService#checkCreditResult(java.lang.Object) 
   */
  @Override
  public Object checkCreditResult(Long custId, Long productId, Object commitOutput) {
    return null;
  }
}
